package com.aaa.gs.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @fileName:MyRandomRule
 * @description: 自定义的负载均衡策略
 * @author:忆尘
 * @createTime:2020/11/4 15:03
 * @version:1.0.0
 */

public class MyRandomRule extends AbstractLoadBalancerRule {
    public MyRandomRule() {
    }

    //SupperssWarnings 抑制警告
    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        System.out.println("lb:---------"+lb+"-------lb--------end!!");
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                //Thread.interrupted()  判断是否线程中断
               //Thread t = new Thread();  面试题通过类 判断和通过对象判断线程中断有什么区别
               //t.isInterrupted();
                if (Thread.interrupted()) {
                    return null;
                }
                //获取可用的负载均衡对象
                List<Server> upList = lb.getReachableServers();
                System.out.println("可用的："+upList);
                //获取所有
                List<Server> allList = lb.getAllServers();
                System.out.println("所有的："+allList);
                //获取所有总数量
                int serverCount = allList.size();
                System.out.println("所有负载均衡服务器数量"+serverCount);//3
                if (serverCount == 0) {
                    return null;
                }

                int index = this.chooseRandomInt(serverCount);
                //选择的服务器下标为：
                System.out.println("选择的服务器下标为"+index);
                server = (Server)upList.get(index);
                if (server == null) {
                    //让出当前线程的CPU，让其他线程执行
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        //ThreadLocalRandom 线程安全的
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }



    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        System.out.println(ThreadLocalRandom.current().nextInt(30));
    }
}
